package fr.gdi.android.news;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import fr.gdi.android.news.ShareReceiverProxyAdapter.ShareReceiverProxy;
import fr.gdi.android.news.utils.Constants;
import fr.gdi.android.news.utils.Constants.Configuration;
import fr.gdi.android.news.utils.Constants.ExtraTags;
import fr.gdi.android.news.utils.Constants.Preferences;
import fr.gdi.android.news.utils.IOUtils;
import fr.gdi.android.news.utils.PreferenceUtils;
import fr.gdi.android.news.utils.Utils;

public class ReadMoreActivity extends Activity
{
    private static final String ORIGINAL_URL = "ORIGINAL_URL";

    private static final int ADAPTER_DIALOG = 1;
    
    private WebView browser;
    
    private String url, title, originalUrl;
    
    private View buttonBar;
    private View adapterView;
    //private View buttonShare;
    
    private LinearLayout buttonShareWrapper;
    
    private TextView noAdapterWarningView;

    private ListView adapterList;

    private ImageView buttonNext;
    private ImageView buttonPrev;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        final ReadMoreActivity context = this;
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.news_widget_readmore);
        
        browser = (WebView) findViewById(R.id.feed_browser);
        
        final Activity activity = this;
        relocateCache(); 
        
        buttonBar = findViewById(R.id.button_bar);
        //buttonShare = findViewById(R.id.button_share);
        buttonShareWrapper = (LinearLayout) buttonBar.findViewById(R.id.button_share_wrapper);
        buttonPrev = (ImageView) findViewById(R.id.left);
        buttonNext = (ImageView) findViewById(R.id.right);
        
        configureButtonBar(context);
        
        configureBrowser(activity);
    };


    private void configureBrowser(final Activity activity)
    {
        browser.getSettings().setAppCacheEnabled(true);
        browser.getSettings().setLightTouchEnabled(true);
        browser.getSettings().setSupportZoom(true);
        browser.getSettings().setJavaScriptEnabled(true);
        //browser.getSettings().setBuiltInZoomControls(true);
        browser.getSettings().setPluginsEnabled(true);
        browser.getSettings().setSupportMultipleWindows(false);
        //browser.getSettings().setAppCachePath(appCachePath);
        browser.setVerticalScrollBarEnabled(false);
        browser.setHorizontalScrollBarEnabled(false);
        
        browser.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
                activity.setProgress(progress * 100);
            }
        });
        
        browser.setWebViewClient(new WebViewClient() {
            
            
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
            
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                buttonPrev.setImageResource(browser.canGoBack() ? R.drawable.ic_left : R.drawable.ic_left_disabled);
                buttonNext.setImageResource(browser.canGoForward() ? R.drawable.ic_right : R.drawable.ic_right_disabled);
                
            }
        });
        
        onNewIntent(getIntent());
    }
        
    public void onBackPressed()
    {
        
        if (browser.isFocused() && browser.canGoBack()) 
        {
            browser.goBack();                      
        }      
        else 
        {
            super.onBackPressed();
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        final Bundle extras = intent.getExtras();
        if (extras != null)
        {
            if ( !TextUtils.equals(extras.getString(ExtraTags.TAG_URL), this.originalUrl) ) 
            {
                this.url = extras.getString(ExtraTags.TAG_URL);
                this.title = extras.getString(ExtraTags.TAG_NAME);
                this.originalUrl = extras.getString(ORIGINAL_URL);
                browser.loadUrl(url);
                this.setTitle(title);
            }
        }
        else
        {
            finish();
        }
    }

    private void configureButtonBar(final ReadMoreActivity context)
    {
        /*
        buttonShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
             
                if ( adapterView == null ) 
                {
                    LayoutInflater inflater = getLayoutInflater();
                    adapterView = inflater.inflate(R.layout.share_adapter_dialog, null);
                    noAdapterWarningView = (TextView) adapterView.findViewById(R.id.no_adapter_warning);
                    adapterList = (ListView) adapterView.findViewById(R.id.adapter_list);
                }
                
                List<ShareReceiverProxy> activities = PreferenceUtils.getShareActivities(context); 
                if ( activities.size() > 0 ) 
                {
                    noAdapterWarningView.setVisibility(View.GONE);
                    adapterList.setVisibility(View.VISIBLE);
                    List<ShareReceiverProxyAdapter.ShareReceiverProxy> proxies = new ArrayList<ShareReceiverProxyAdapter.ShareReceiverProxy>(); 
                    for (ShareReceiverProxy item : activities)
                    {
                        if ( !item.isDisabled() ) 
                        {
                            proxies.add(item);
                        }
                    }
                    if ( proxies.size() > 0 ) 
                    {
                        adapterList.setAdapter(new ShareReceiverProxyAdapter(context, proxies));
                    }
                    else 
                    {
                        noAdapterWarningView.setVisibility(View.VISIBLE);
                        adapterList.setVisibility(View.GONE);
                    }
                }
                else 
                {
                    noAdapterWarningView.setVisibility(View.VISIBLE);
                    adapterList.setVisibility(View.GONE);
                }
                context.showDialog(ADAPTER_DIALOG);
            }
        });
        */
        buttonPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if ( browser.canGoBack() ) browser.goBack();
            }
        });
        
        buttonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0)
            {
                if ( browser.canGoForward() ) browser.goForward();
            }
        });
        
        final Handler handler = new Handler();
        final Runnable hideButtonTask = new Runnable() {
            @Override
            public void run()
            {
                buttonBar.setVisibility(View.GONE);
            }
        };
        
        browser.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1)
            {
                buttonBar.setVisibility(View.VISIBLE);
                
                buttonShareWrapper.removeAllViews();
                List<ShareReceiverProxy> activities = PreferenceUtils.getShareActivities(context); 
                if ( activities.size() > 0 ) 
                {
                    for (final ShareReceiverProxy shareReceiverProxy : activities)
                    {
                        if ( shareReceiverProxy.isDisabled() ) continue;
                        
                        Drawable d = shareReceiverProxy.icon;
                        ImageView iv = new ImageView(ReadMoreActivity.this);
                        iv.setAlpha(154);
                        iv.setMaxWidth(16);
                        iv.setMaxHeight(16);
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(48, 48);
                        lp.setMargins(0, 10, 0, 0);
                        iv.setLayoutParams(lp);
                        iv.setScaleType(ScaleType.FIT_XY);
                        iv.setImageDrawable(d);
                        iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View arg0)
                            {
                                ComponentName cn = new ComponentName(shareReceiverProxy.receiverPackage, shareReceiverProxy.receiverName);
                                Intent intent = new Intent(Constants.Actions.SHARE).setComponent(cn);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                intent.putExtra("url", context.originalUrl);
                                intent.putExtra("title", context.title);
                                context.startActivity(intent);
                            }
                        });
                        buttonShareWrapper.addView(iv);
                    }
                    buttonShareWrapper.setVisibility(View.VISIBLE);
                }
                else
                {
                    buttonShareWrapper.setVisibility(View.GONE);
                }
                
                handler.removeCallbacks(hideButtonTask);
                handler.postDelayed(hideButtonTask, 3000);
                
                return false;
            }
        });
    }
    /*
    @Override
    protected Dialog onCreateDialog(int id)
    {
        final ReadMoreActivity context = this;
        
        switch ( id ) 
        {
            case ADAPTER_DIALOG:
            {

                if ( adapterView == null ) 
                {
                    LayoutInflater inflater = getLayoutInflater();
                    adapterView = inflater.inflate(R.layout.share_adapter_dialog, null);
                    noAdapterWarningView = (TextView) adapterView.findViewById(R.id.no_adapter_warning);
                    adapterList = (ListView) adapterView.findViewById(R.id.adapter_list);
                }
                
                final Dialog dlg = new Dialog(this);
                //noAdapterWarningView.setText(Html.fromHtml(this.getText(R.string.no_share_adapter_found).toString()));
                noAdapterWarningView.setText(R.string.no_share_adapter_found);
                noAdapterWarningView.setMovementMethod(LinkMovementMethod.getInstance());
                noAdapterWarningView.setFadingEdgeLength(0);
                noAdapterWarningView.setVerticalFadingEdgeEnabled(false);
                
                adapterList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> v, View convertView, int position, long id)
                    {
                        ShareReceiverProxy item = (ShareReceiverProxy) adapterList.getAdapter().getItem(position);

                        ComponentName cn = new ComponentName(item.receiverPackage, item.receiverName);
                        Intent intent = new Intent(Constants.Actions.SHARE).setComponent(cn);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY);
                        intent.putExtra("url", context.originalUrl);
                        intent.putExtra("title", context.title);
                        context.startActivity(intent);
                        dlg.cancel();
                    }
                });
                
                dlg.setTitle(this.getText(R.string.select_share_adapter));
                dlg.getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                dlg.setContentView(adapterView);
                return dlg;
            }
        }
        return super.onCreateDialog(id);
    }
    */
    private void relocateCache()
    {
        if ( !PreferenceUtils.getBooleanPreference(this, Preferences.CACHE_TO_SD) ) return;
        
        String appCachePath = new File(IOUtils.getCacheDir(), "webview").getAbsolutePath();
        String expectedPath = "/data/data/fr.gdi.android.news/cache/webviewCache";
        
        File f = new File(expectedPath);
        
        if ( f.exists() && !IOUtils.isSymlink(f) )
        {
            IOUtils.delete(f);
        }
        
        if ( !f.exists() )
        {
            try 
            {
                Runtime.getRuntime().exec(new String[] {"ln", "-s", appCachePath});
            } 
            catch(java.io.IOException ioe) 
            {
                //swallow
            }
        }
    }
    
    public static void open(Context context, String link, String title, String preferredAction)
    {
        if (!Utils.isOnline(context)) return;
        
        if (TextUtils.isEmpty(link))
        {
            Log.w(ReadMoreActivity.class.getName(), "News link is null. It should not happen, yet it did. Aborting");
            return;
        }
        
        String originalUrl = link;
        link = getLink(context, link);
        
        if (!TextUtils.equals(preferredAction, Configuration.USE_BUILTIN_BROWSER))
        {
            try
            {
                String[] parts = preferredAction.split("\\/");
                ComponentName cn = new ComponentName(parts[0], parts[1]);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)).setComponent(cn);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            catch (Exception e)
            {
                Log.e(ReadMoreActivity.class.getName(), "Unable to start preferred activity", e);
                startDefaultActivity(context, link, title, originalUrl);
            }
        }
        else
        {
            startDefaultActivity(context, link, title, originalUrl);
        }
    }
    
    private static String getLink(Context context, String link)
    {
        String mobilizer = PreferenceUtils.getStringPreference(context, Preferences.MOBILIZER_KEY, null, Configuration.NO_MOBILIZER);
        if (TextUtils.equals(mobilizer, Configuration.GOOGLE))
        {
            String encoded = URLEncoder.encode(link);
            link = "http://www.google.com/gwt/x?u=" + encoded;
            if (!PreferenceUtils.getBooleanPreference(context, Preferences.MOBILIZER_SHOW_IMAGES))
            {
                link += "&noimg=1";
            }
        }
        if (TextUtils.equals(mobilizer, Configuration.INSTAPAPER))
        {
            String encoded = URLEncoder.encode(link);
            link = "http://www.instapaper.com/m?u=" + encoded;
        }
        if (TextUtils.equals(mobilizer, Configuration.INSTAPAPER_TEXT))
        {
            String encoded = URLEncoder.encode(link);
            link = "http://www.instapaper.com/text?u=" + encoded;
        }
        return link;
    }
    
    
    
    private static void startDefaultActivity(Context context, String link, String title, String originalUrl)
    {
        Intent intent = new Intent(context, ReadMoreActivity.class);
        intent.putExtra(ExtraTags.TAG_URL, link);
        intent.putExtra(ExtraTags.TAG_NAME, title);
        intent.putExtra(ORIGINAL_URL, originalUrl);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }
    
    @Override
    public void finish()
    {
        clearCache();
        super.finish();
    }
    
    private void clearCache()
    {
        if (browser != null && PreferenceUtils.getBooleanPreference(this, Preferences.CLEAR_CACHE_ON_EXIT))
        {
            browser.clearCache(true);
        }
    }
    
    @Override
    protected void onUserLeaveHint()
    {
        clearCache();
        super.onUserLeaveHint();
    }
}
